package com.wdh.kjs.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.wdh.kjs.R;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.ToastUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

/**
 * Created by CQH on 2016/4/21.
 */
public class UploadIdCardActivity extends BaseTopActivity implements View.OnClickListener {
    private Button exitLogin;
    private ImageView upload_portrait;
    private LinearLayout ll_pc_take_photo, ll_pc_pick_photo, ll_pc_cancel;
    private PopupWindow popwindow;
    private Button bt_activity_uploadId_push;

    private String fileDir = "/sdcard/kjs2/";
    private String voucherUrl = "";
    private File tempFile = null;
    private Bitmap bitmap;
    private Uri pictureUri = null;
    private String zhanghu;
    private String mima;
    private JsonModel jsonModel;
    private SharedPreferences sharedPreferences;
    private ImageView iv_voucher;
    private TextView tv_description;
private TextView tv_upload_tupian;
    private String  filePath="";
    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 27;
    private String title="";
    private String description="";
    private String url;
    private String tupianid;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload_idcard);

        Intent intent=getIntent();
        title=intent.getStringExtra("title");
        description=intent.getStringExtra("description");
        tupianid=intent.getStringExtra("id");
        initTopBar(title);
        initview();
        SharedPreferences sharedPreferences=getSharedPreferences("benditupian", MODE_PRIVATE);
        switch (tupianid){
            case "0":
                url=sharedPreferences.getString("tupian0", "");
                break;
            case "1":
                url=sharedPreferences.getString("tupian1", "");
                break;
            case "2":
                url=sharedPreferences.getString("tupian2", "");
                break;
        }
        fangtupian(url);


    }
private void fangtupian(String string){
    if(!url.equals("")){
        tv_upload_tupian.setVisibility(View.GONE);
        iv_voucher.setVisibility(View.VISIBLE);
        try {
            FileInputStream fileInputStream=new FileInputStream(string);
            Bitmap bitmap= BitmapFactory.decodeStream(fileInputStream);
            iv_voucher.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
    private void initview() {
        tv_upload_tupian = (TextView) findViewById(R.id.tv_upload_tupian);
        tv_description = (TextView) findViewById(R.id.tv_RealNameOrg_description);
        tv_description.setText(description);
        iv_voucher = (ImageView) findViewById(R.id.iv_activity_uploadId);
        upload_portrait = (ImageView) findViewById(R.id.upload_portrait);
        upload_portrait.setOnClickListener(this);
        bt_activity_uploadId_push = (Button) findViewById(R.id.bt_activity_uploadId_push);
        bt_activity_uploadId_push.setOnClickListener(this);
    }

    public void onClick(View v) {
        int id=v.getId();
        switch (id)
        {
            case R.id.upload_portrait:{
                showPopWindow();
                darken();
                break;
            }
            case R.id.bt_activity_uploadId_push:{
                if(filePath.equals("")||filePath.length()==0){
                    ToastUtils.show(UploadIdCardActivity.this,"请选择文件",1500);
                }
                else
                {
                    Intent intent=new Intent();
                    intent.setClass(UploadIdCardActivity.this,RealNameAuthOrgActivity.class);
                    intent.putExtra("filepath", filePath);
                    SharedPreferences.Editor editor=getSharedPreferences("benditupian",MODE_PRIVATE).edit();
                    switch (tupianid){
                        case "0":
                            editor.putString("tupian0",filePath);
                            break;
                        case "1":
                            editor.putString("tupian1",filePath);
                            break;
                        case "2":
                            editor.putString("tupian2",filePath);
                            break;
                    }

                    editor.commit();
                    setResult(getResultCode(), intent);
                    finish();
                }
                break;
            }
            default:{
                break;
            }
        }
    }

    private int getResultCode()
    {
        if(title.contains("身份证")){
            return RealNameAuthOrgActivity.RESULTCODE_IdNumFile;
        }
        else if(title.contains("营业")){
            return RealNameAuthOrgActivity.RESULTCODE_BusinessLicenseFile;
        }
        else if(title.contains("开户")){
            return RealNameAuthOrgActivity.RESULTCODE_PermitLicenseFile;
        }
        return RealNameAuthOrgActivity.RESULTCODE_IdNumFile;
    }

    private void showPopWindow() {
        final View contentView = LayoutInflater.from(this).inflate(
                R.layout.view_picture_choose, null);
        ll_pc_take_photo = (LinearLayout) contentView.findViewById(R.id.ll_pc_take_photo);
        ll_pc_pick_photo = (LinearLayout) contentView.findViewById(R.id.ll_pc_pick_photo);
        ll_pc_cancel = (LinearLayout) contentView.findViewById(R.id.ll_pc_cancel);
        ll_pc_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                boolean canUse = true;
                android.hardware.Camera mCamera = null;
                try {
                    mCamera = android.hardware.Camera.open(0);
                    mCamera.setDisplayOrientation(90);
                } catch (Exception e) {
                    canUse = false;
                }
                if (canUse) {
                    mCamera.release();
                    mCamera = null;
                    startActivityForResult(intent, 0);
                    Log.e("ChainWinFinance", "摄像头已打开");
                } else {
                    ToastUtils.showShort(UploadIdCardActivity.this, "请先打开摄像头权限！");
                }

            }
        });
        ll_pc_pick_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent myintent1 = new Intent();
//                /* 开启Pictures画面Type设定为image */
//                myintent1.setType("image/*");
//                /* 使用Intent.ACTION_GET_CONTENT这个Action */
//                myintent1.setAction(Intent.ACTION_GET_CONTENT);
//                /* 取得相片后返回本画面 */
//                startActivityForResult(myintent1, 1);
                if (ContextCompat.checkSelfPermission(UploadIdCardActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(UploadIdCardActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_READ_CONTACTS);
                }else {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 1);
                }
            }
//                Intent intent = new Intent(
//                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(intent, 1);
//
//            }
        });
        ll_pc_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popwindow.dismiss();
            }
        });

        popwindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popwindow.setAnimationStyle(R.style.anim_popup_dir);
        popwindow.setTouchable(true);
        popwindow.setFocusable(true);
        popwindow.setBackgroundDrawable(new BitmapDrawable());
        popwindow.setOutsideTouchable(true);
        popwindow.setOnDismissListener(new poponDismissListener());
        //Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL---屏幕中间
        popwindow.showAtLocation(findViewById(R.id.upload_portrait), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        contentView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = contentView.findViewById(R.id.ll_popup).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        brighten();
                        popwindow.dismiss();
                    }
                }
                return true;
            }
        });

    }

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            brighten();
        }

    }

    private void brighten() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    private void darken() {
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha = 0.7f; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (popwindow != null && popwindow.isShowing()) {
            popwindow.dismiss();
        }
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0) {
                takePhoto(data);
                iv_voucher.setVisibility(View.VISIBLE);
            } else if (requestCode == 1) {
                selectPhoto(data);
                iv_voucher.setVisibility(View.VISIBLE);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    private int getInSampleSize(long i) {
        int inSampleSize = 1;
        if (0 < i && i <= 4)
            inSampleSize = 2;
        else if (4 < i && i <= 16)
            inSampleSize = 4;
        else if (16 < i && i <= 64)
            inSampleSize = 8;
        else if (64 < i && i <= 256)
            inSampleSize = 16;
        else if (256 < i && i <= 1024)
            inSampleSize = 32;
        return inSampleSize;
    }

    public void saveBitmapFile(Bitmap bitmap, File file) {
//        File file = new File(path);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Bitmap getBitmap(File file, String path, int inSampleSize) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, opts);
            opts.inSampleSize = inSampleSize;
            opts.inJustDecodeBounds = false;
            Bitmap btp = BitmapFactory.decodeStream(stream, null, opts);
            return btp;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void copyfile(File fromFile, File toFile, Boolean rewrite) {
        if (!fromFile.exists()) {
            return;
        }
        if (!fromFile.isFile()) {
            return;
        }
        if (!fromFile.canRead()) {
            return;
        }
        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }
        if (toFile.exists() && rewrite) {
            toFile.delete();
        }
        //当文件不存时，canWrite一直返回的都是false
        // if (!toFile.canWrite()) {
        // MessageDialog.openError(new Shell(),"错误信息","不能够写将要复制的目标文件" + toFile.getPath());
        // Toast.makeText(this,"不能够写将要复制的目标文件", Toast.LENGTH_SHORT);
        // return ;
        // }
        try {
            java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);
            java.io.FileOutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c); //将内容写到新文件当中
            }
            fosfrom.close();
            fosto.close();
        } catch (Exception ex) {
            Log.e("readfile", ex.getMessage());
        }
    }

    /**
     * 照相得到图片
     * @param data
     */
    private void takePhoto(Intent data)
    {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        Bundle bundle = data.getExtras();
        Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
        FileOutputStream b = null;
        //???????????????????????????????为什么不能直接保存在系统相册位置呢？？？？？？？？？？？？
        File file = new File(fileDir);
        file.mkdirs();// 创建文件夹
        String fileName = fileDir + name;
        try {
            b = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        voucherUrl = fileName;
        File picture = new File(fileName);
        String absolutePath = picture.getAbsolutePath();
        String time = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "";
        filePath = picture.getParent() + "/" + "pick" + time + absolutePath.substring(absolutePath.lastIndexOf("."));
        Log.e("ChainWinFinance", "DDDfilePath" + filePath);
        tempFile = new File(filePath);
        try {
            tempFile.createNewFile();//必须要执行
        } catch (IOException e) {
            e.printStackTrace();
        }
        copyfile(picture, tempFile, true);
        if (tempFile.exists()) {
            try {
//                        ToastUtils.showShort(CompletedTransferActivity.this, "已选择图片：" + fileName);
                if (iv_voucher != null && iv_voucher.getDrawable() != null) {

                    Bitmap oldBitmap = ((BitmapDrawable) iv_voucher.getDrawable()).getBitmap();

                    iv_voucher.setImageDrawable(null);

                    if (oldBitmap != null) {
                        oldBitmap.recycle();
                        Log.e("ChainWinFinance", "内存回收！");
                        oldBitmap = null;
                    }
                }
                FileInputStream stream = new FileInputStream(tempFile);
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(filePath, opts);
                opts.inSampleSize = computeSampleSize(opts, -1, 130 * 130);
                opts.inJustDecodeBounds = false;
                Bitmap btp = BitmapFactory.decodeStream(stream, null, opts);
                iv_voucher.setImageBitmap(btp);
                long size = tempFile.length(); // 大小 bytes
                long temp = 1024 * 1024 * 2;
                int inSampleSize = 1;
                if (size > temp) {
                    Log.e("ChainWinFinance", "上传压缩");
                    long i = size / temp;
                    inSampleSize = getInSampleSize(i);
                    bitmap = getBitmap(tempFile, filePath, inSampleSize);
                    saveBitmapFile(bitmap, tempFile);
                    Log.e("ChainWinFinance", "inSampleSize:" + inSampleSize);
                    Log.e("ChainWinFinance", "tempFile.length()压缩后:" + tempFile.length() / (1024 * 1024));
                }
                Log.e("ChainWinFinance", "上传图片大小" + tempFile.length());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else
            ToastUtils.showShort(UploadIdCardActivity.this, "文件不存在！");
    }


    /**
     * 从相册中中选择图片
     * @param data
     */
    private void selectPhoto(Intent data){
        if (data != null) {
            Uri uri = data.getData();
            String fileType = uri.getScheme();
            if (!fileType.equals("file")) {
                if (iv_voucher != null && iv_voucher.getDrawable() != null) {

                    Bitmap oldBitmap = ((BitmapDrawable) iv_voucher.getDrawable()).getBitmap();

                    iv_voucher.setImageDrawable(null);

                    if (oldBitmap != null) {

                        oldBitmap.recycle();
                        Log.e("ChainWinFinance", "内存回收！");
                        oldBitmap = null;

                    }
                }
                String path;
                if (!android.text.TextUtils.isEmpty(uri.getAuthority())) {
                    Cursor cursor = UploadIdCardActivity.this.getContentResolver().query(uri,
                            new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                    if (null == cursor) {
                        Toast.makeText(UploadIdCardActivity.this, "图片没找到", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    cursor.moveToFirst();
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    cursor.close();
                } else {
                    path = uri.getPath();
                }
//                      iv_voucher.setImageURI(Uri.parse(path));
                File picture = new File(path);
                String filename = picture.getAbsolutePath();
                String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "";
                filePath = picture.getParent() + "/" + name + filename.substring(filename.lastIndexOf("."));
                tempFile = new File(filePath);
                try {
                    tempFile.createNewFile();//必须要执行
                } catch (IOException e) {
                    e.printStackTrace();
                }
                copyfile(picture, tempFile, true);
                Log.e("ChainWinFinance", "图片大小" + tempFile.length());
                Log.e("ChainWinFinance", "图片大小:" + tempFile.length() / (1024 * 1024) + "兆");
                if (tempFile.exists()) {
                    try {
                        ToastUtils.showShort(UploadIdCardActivity.this, "已选择图片：" + path);
                        FileInputStream stream = new FileInputStream(tempFile);
                        BitmapFactory.Options opts = new BitmapFactory.Options();
                        opts.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(filePath, opts);
                        opts.inSampleSize = computeSampleSize(opts, -1, 130 * 130);
                        opts.inJustDecodeBounds = false;
                        Bitmap btp = BitmapFactory.decodeStream(stream, null, opts);
                        Log.e("ChainWinFinance", "inSampleSize:" + opts.inSampleSize);
                        iv_voucher.setImageBitmap(btp);
                        long size = tempFile.length(); // 大小 bytes
                        long temp = 1024 * 1024 * 2;
                        int inSampleSize = 1;
                        if (size > temp) {
                            Log.e("ChainWinFinance", "上传压缩");
                            long i = size / temp;
                            inSampleSize = getInSampleSize(i);
                            bitmap = getBitmap(tempFile, filePath, inSampleSize);
                            saveBitmapFile(bitmap, tempFile);
                            Log.e("ChainWinFinance", "inSampleSize:" + inSampleSize);
                            Log.e("ChainWinFinance", "tempFile.length()压缩后:" + tempFile.length() / (1024 * 1024));
                        }
                        pictureUri = uri;
                        Log.e("ChainWinFinance", "上传图片大小" + tempFile.length());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else
                    ToastUtils.showShort(UploadIdCardActivity.this, "文件不存在！");
            } else
                ToastUtils.showShort(UploadIdCardActivity.this, "不能上传云上的图片，请选择本地图片！");
        } else {
            Toast.makeText(UploadIdCardActivity.this, "图片没找到", Toast.LENGTH_SHORT).show();
            return;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
//            case MY_PERMISSIONS_REQUEST_STORAGE_CODE: {
//                // If request is cancelled, the result arrays are empty.
//                if (grantResults.length > 0
//                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//                boolean canUse = true;
//                android.hardware.Camera mCamera = null;
//                try {
//                    mCamera = android.hardware.Camera.open(0);
//                    mCamera.setDisplayOrientation(90);
//                } catch (Exception e) {
//                    canUse = false;
//                }
//                if (canUse) {
//                    mCamera.release();
//                    mCamera = null;
//                    startActivityForResult(intent, 0);
//                    Log.e("ChainWinFinance", "摄像头已打开");
//                } else {
//
//                    ToastUtils.showShort(CompletedTransferActivity.this, "请先打开摄像头权限！");
//                }
//                    // permission was granted, yay! Do the
//                    // contacts-related task you need to do.
//
//                } else {
//
//                    // permission denied, boo! Disable the
//                    // functionality that depends on this permission.
//                }
//
//            }
//            break;
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS:

                if (grantResults.length>0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Intent intent = new Intent(
                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 1);
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(UploadIdCardActivity.this, "权限错误，无法正常工作！", Toast.LENGTH_SHORT).show();
                }
                return;


        }

    }

}